const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const whiteList = ['b.ahhh.cn']
http.createServer((req,res)=>{
  let {pathname} = url.parse(req.url)
  let filePath = path.join(__dirname,pathname);
  fs.stat(filePath,function(err,statObj){
    if(err){
      res.statusCode = 404;
      res.end();
      return
    }
    if(statObj.isFile()){
      // mime  header
      if(/(\.jpg)|(\.png)$/.test(pathname)){
        //referer -> http://b.ahhh.cn:3000/index.html 从哪里引用的
        let referer = req.headers['referer'] || req.headers['referrer']; //emmm 最好两个都写上
        //req.headers.host -> a.ahhh.cn:3000 请求的网址的域名
        if(referer){
          let refererHostName = url.parse(referer).hostname; //referer里的url是带协议和主机名的，而url模块在有协议和主机名时是能解析出hostname的，只是我们通常通过req.url拿到的是端口号之后hash之前的(即显示在请求行中的url)，故会产生错误的认知
          /*
            const url = require('url');
            const x = 'http://b.ahhh.cn:3000/index.html'
            Url {
              protocol: 'http:',
                slashes: true,
                auth: null,
                host: 'b.ahhh.cn:3000',
                port: '3000',
                hostname: 'b.ahhh.cn',
                hash: null,
                search: null,
                query: null,
                pathname: '/index.html',
                path: '/index.html',
                href: 'http://b.ahhh.cn:3000/index.html' }*/
          let hostName = req.headers.host.split(':')[0]; //通过req.headers.host拿到的主机名是带端口号的(如果你输入url地址时带了的话)（而通过url.parse解析的手动给与的完整url想要拿到端口号需要.port）
          if(refererHostName === hostName || whiteList.includes(refererHostName)){
            fs.createReadStream(filePath).pipe(res);
          }else{
            fs.createReadStream(path.resolve(__dirname,'2.jpg')).pipe(res);
          }
        }else{
          fs.createReadStream(filePath).pipe(res);
        }
      }else{ //直接打开图片 而不是被引用
        fs.createReadStream(filePath).pipe(res);
      }
      return
    }else{
      res.statusCode = 404;
      res.end();
      return
    }
  })
}).listen(3000);
